package com.ds.robot.assistant.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.ds.robot.assistant.entity.EmpInfoEntity;
import com.ds.robot.assistant.entity.ProjectInfoEntity;
import com.ds.robot.assistant.entity.QxUserEntity;
import com.ds.robot.assistant.service.EmpInfoService;
import com.ds.robot.assistant.service.ProjectInfoService;
import com.ds.robot.assistant.service.QxUserService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Configuration
@Slf4j
public class CacheConfig {

    @Autowired
    private EmpInfoService empInfoService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private QxUserService qxUserService;

    @Bean
    public LoadingCache<String, String> userCache() {
        return CacheBuilder.newBuilder()
                .maximumSize(1000) // 最大缓存条目数量
                .expireAfterWrite(12, TimeUnit.HOURS) // 写入后12小时过期
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(@NotNull String key) throws Exception {
                        return loadUserFromDatabase(key);
                    }
                });
    }

    private String loadUserFromDatabase(String key) {
        log.info("====没有命中userCache，loadEmpFromDatabase, key={}", key);
        EmpInfoEntity one = empInfoService.lambdaQuery().eq(EmpInfoEntity::getAccountId, key).one();
        return Optional.ofNullable(one).map(EmpInfoEntity::getName).orElse(null);
    }


    @Bean
    public LoadingCache<String, ProjectInfoEntity> projectCache() {
        return CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(12, TimeUnit.HOURS)
                .build(new CacheLoader<String, ProjectInfoEntity>() {
                    @Override
                    public ProjectInfoEntity load(@NotNull String key) throws Exception {
                        return loadProjectFromDatabase(key);
                    }
                });
    }

    private ProjectInfoEntity loadProjectFromDatabase(String key) {
        log.info("====没有命中projectCache，尝试从数据库加载项目信息, key={}", key);
        try {
            return projectInfoService.getOne(new QueryWrapper<ProjectInfoEntity>().eq("space_id", key));
        } catch (Exception e) {
            log.error("从数据库加载项目信息失败, key={}", key, e);
            throw new RuntimeException("数据库查询异常", e);
        }
    }


    @Bean
    public LoadingCache<String, String> qxUserCache() {
        return CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(12, TimeUnit.HOURS)
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(@NotNull String key) {
                        try {
                            return loadQxUserFromDatabase(key);
                        } catch (Exception e) {
                            log.error("Failed to load qx user from database with key: {}", key, e);
                            throw new RuntimeException("Failed to load qx user", e);
                        }
                    }
                });
    }


    private String loadQxUserFromDatabase(String key) {
        log.info("====没有命中qxUserCache，loadQxUserFromDatabase, key={}", key);
        return Optional.ofNullable(qxUserService.getOne(new QueryWrapper<QxUserEntity>().eq("name", key)))
                .map(QxUserEntity::getUserid).orElse(null);
    }

}
